package com.cyou.dream.rule;

import com.cyou.dream.application.ApplicationCommon;
import com.cyou.dream.context.RuleContext;
import com.cyou.dream.core.IRule;
import com.cyou.dream.define.ERule;
import com.cyou.dream.define.ERuleParam;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collections;
import java.util.List;

/**
 * IncrementCounterRule 类实现了自增计数器规则。
 * <p>
 * 该规则用于每次调用时将某个键的值加1，且过期时间为-1（永不过期）。
 * <p>
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class IncrementCounterRule implements IRule {

    @Override
    public boolean evaluate(RuleContext context) {

        Object[] args = {
                context.getRuleParams().get(ERuleParam.THRESHOLD.getKey()),
        };

        List<String> keys = Collections.singletonList(context.getActualKey());

        RedisTemplate redisTemplate = ApplicationCommon.context().getBean("redisTemplate", RedisTemplate.class);

        Long result = (Long) redisTemplate.execute(
                ERule.INCREMENT_COUNTER.getRuleScript(),
                keys,
                args
        );

        return result == 1;
    }
}
